/**
 *  created by jsq on 2017/12/18
 */
import React from 'react'
import {connect} from 'react-redux'
import {messages} from "share/common";
import {Button, Input, Switch, Select, Form, Row, Col, Icon, message, notification} from 'antd';
import vendorService from 'containers/financial-management/supplier-management/vendorService';
import 'styles/financial-management/supplier-management/new-update-bank-account.scss'
import Chooser from "components/chooser";

const FormItem = Form.Item;
const {TextArea} = Input;
const Option = Select.Option;

class NewUpdateBankAccount extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      isEnabled: true,
      isMainAccount: true,
      firstRender: true,
      bankInfo: {},
      bank: [],
      country: [],
      address: [],
      ctripList: [],// 账号标志
    };
  }

  getValueList = () => {
    this.getSystemValueList(2216)
      .then(res => {
        this.setState({
          ctripList: res.data.values
        })
      });
  };

  componentWillMount() {
    this.getValueList();
    let params = this.props.params;
    if (JSON.stringify(params) !== '{}') {
      //编辑
      this.props.form.setFieldsValue({venBankAccountBeans: params.bankName});
      params.bankDefaultName = [
        {
          bankCode: params.bankCode,
          bankTypeBankCode: params.bankType + params.bankCode,
          bankBranchName: params.bankName
        }
      ];
      this.setState({
        bankInfo: params,
        isEnabled: params.venType === 1001 ? true : false,
        isMainAccount: params.primaryFlag
      })
    } else {
      notification.close('section');
      this.setState({loading: false});
      this.props.form.resetFields();
    }

  }

  componentWillReceiveProps(nextProps) {
    let params = nextProps.params;
    if (JSON.stringify(params) === '{}') {
      this.props.form.resetFields();
      notification.close('section');
      this.setState({
        isEnabled: true,
        isMainAccount: true
      })
    }
  }

  statusChange = () => {
    this.setState((prevState) => ({
      isEnabled: !prevState.isEnabled
    }))
  };

  mainAccountChange = () => {
    this.setState((prevState) => ({
      isMainAccount: !prevState.isMainAccount
    }))
  };

  handleNotification = (values) => {
    notification.close('section');
    values.constraintFlag = 'go';
    let method = null;
    if (typeof this.state.bankInfo.id !== 'undefined') {
      values.id = this.state.bankInfo.id;
      method = vendorService.updateBankCardInfo(values)
    } else {
      method = vendorService.addBankCardInfo(values)
    }
    method.then(response => {
      if (response.data.code === '0000') {
        this.props.form.resetFields();
        this.setState({loading: false});
        this.props.close(true);
      } else {
        message.warning(`保存失败,${respone.data.msg}`);
        this.setState({loading: false});
        return;
      }
    }).catch(e => {
      if (e.response) {
        if (typeof this.state.bankInfo.id === 'undefined') {
          message.error(`${messages('common.save.filed')}, ${!!e.response.data.message ? e.response.data.message : e.response.data.errorCode}`);
        } else {
          message.error(`${messages('common.operate.filed')}, ${!!e.response.data.message ? e.response.data.message : e.response.data.errorCode}`);
        }
        this.setState({loading: false});
      }
    })
  };

  handleSubmit = (e) => {
    e.preventDefault();

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({loading: true});
        values.venInfoId = this.props.params.vendorId;
        values.bankCode = values.venBankAccountBeans[0].bankCode;
        values.bankName = values.venBankAccountBeans[0].bankBranchName;
        values.bankType = values.venBankAccountBeans[0].bankType;
        values.companyOid = this.props.company.companyOID;
        values.venType = values.isEnabled ? 1001 : 1002;
        values.venOperatorNumber = this.props.user.employeeID;
        values.venOperatorName = this.props.user.fullName;

        values.bankOpeningCity = values.bankAddress;

        let method = null;
        if (typeof this.state.bankInfo.id !== 'undefined') {
          //编辑
          values.id = this.state.bankInfo.id;
          method = vendorService.updateBankCardInfo(values)
        } else {
          method = vendorService.addBankCardInfo(values)
        }
        method.then(response => {
          if (response.data.constraintFlag === 'false') {
            //弹框出提示
            notification.open({
              message: <span>{messages('financial-management.key307'/*供应商*/)}<span style={{color: '#2292dd'}}>
                {response.data.venInfoName}</span>{messages('financial-management.key308'/*下已有启用的*/)}
                <span
                  style={{color: '#2292dd'}}>{response.data.mesBankName}</span>{messages('financial-management.key309'/*主账户*/)}
                <span style={{color: '#2292dd'}}>{response.data.mesVenBankNumberName}</span>
              </span>,
              description: <span>{messages('financial-management.key310'/*点击【继续】，自动将主账户*/)}<span
                style={{color: '#2292dd'}}>
                {response.data.mesVenBankNumberName}</span>
                {messages('financial-management.key311'/*设置为非主账户*/)}
              </span>,
              icon: <Icon type="exclamation-circle" style={{color: '#faad14'}}/>,
              duration: 0,
              key: 'section',
              btn:
                <div>
                  <Button size="small" onClick={() => {
                    this.setState({loading: false});
                    notification.close('section')
                  }}>
                    {messages('common.cancel')}
                  </Button>
                  <Button type="primary" style={{marginLeft: 10}} size="small"
                          onClick={() => this.handleNotification(response.data)}>
                    {messages('financial-management.key312'/*继续*/)}
                  </Button>
                </div>
            });
          } else {
            if (response.data.code === '0000') {
              if (typeof this.state.bankInfo.id === 'undefined') {
                message.success(messages('financial-management.key313'/*保存成功！*/)); /*保存成功！*/
              } else {
                message.success(`${messages('common.operate.success')}`);
              }
              this.props.form.resetFields();
              this.setState({
                loading: false,
                isEnabled: true,
                isMainAccount: true
              });
              this.props.close(true);
            } else {
              message.warning(`${messages('common.save.filed')},${response.data.msg}`);
              this.setState({loading: false});
              return;
            }
          }
        }).catch(e => {
          if (e.response) {
            if (typeof this.state.bankInfo.id === 'undefined') {
              message.error(`${messages('common.save.filed')}, ${!!e.response.data.message ? e.response.data.message : e.response.data.errorCode}`);
            } else {
              message.error(`${messages('common.operate.filed')}, ${!!e.response.data.message ? e.response.data.message : e.response.data.errorCode}`);
            }
            this.setState({loading: false});
          }
        });
      }
    })
  };

  //切换银行
  handleBankChange = (value) => {
    if (value && value.length === 0) {
      return;
    }
    if (typeof value[0].id !== 'undefined') {
      let bankInfo = this.state.bankInfo;
      bankInfo.country = bankInfo.countryCode;
      this.setState({bankInfo});
      //选择一个银行后，把国家与地址填充过去
      this.props.form.setFieldsValue({
        country: value[0].countryName,
        bankAddress: value[0].province + "-" + value[0].city
      })
    }
  };

  onCancel = () => {
    this.props.close(false);
    this.props.form.resetFields();
    notification.close('section');
    this.setState({loading: false});
  };
  renderCtripAccountOption = (data) => {
    if (data && data.length) {
      return data.map((item) => {
        return <Option value={item.value} key={item.code}>{item.messageKey}</Option>
      })
    } else {
      return (<Option value={""} key={1}>{""}</Option>)
    }
  };

  render() {

    const {getFieldDecorator} = this.props.form;
    const {loading, isEnabled, isMainAccount, bank, bankInfo, country, address} = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 0},
    };
    return (
      <div className="new-update-bank-account">
        <Form onSubmit={this.handleSubmit}>
          <div className="basic-title">
            {messages('financial-management.key314'/*基础信息*/)}
          </div>
          <Row gutter={24} className="new-update-bank-account-formItem1">
            <Col offset={4} span={7}>
              <FormItem {...formItemLayout}
                        label={messages('common.column.status')} colon={true}>
                {getFieldDecorator('isEnabled', {
                  valuePropName: "checked",
                  initialValue: isEnabled
                })(
                  <div>
                    <Switch checked={isEnabled}
                            checkedChildren={<Icon type="check"/>}
                            unCheckedChildren={<Icon type="cross"/>} onChange={this.statusChange}/>
                    <span className="enabled-type" style={{marginLeft: 20, width: 100}}>
                      {isEnabled ? messages('common.status.enable') : messages('common.disabled')}
                    </span>
                  </div>)}
              </FormItem>
            </Col>
            <Col span={8} offset={1}>
              <FormItem {...formItemLayout}
                        label={messages('financial-management.key315'/*主账户*/)} colon={true}>
                {getFieldDecorator('primaryFlag', {
                  valuePropName: "checked",
                  initialValue: isMainAccount
                })(
                  <div>
                    <Switch checked={isMainAccount}
                            checkedChildren={<Icon type="check"/>}
                            unCheckedChildren={<Icon type="cross"/>}
                            onChange={this.mainAccountChange}/>
                    <span className="enabled-type" style={{marginLeft: 20, width: 100}}>
                      {isMainAccount ? messages('financial-management.key316'/*是*/) : messages('financial-management.key317'/*否*/)}
                    </span>
                  </div>)}
              </FormItem>
            </Col>
          </Row>

          {/*银行*/}
          <Row gutter={22}>
            <Col span={22}>
              <FormItem {...formItemLayout}
                        label={messages('financial-management.key303'/*银行名称*/)} colon={true}>
                {getFieldDecorator('venBankAccountBeans', {
                  initialValue: bankInfo.bankDefaultName,
                  rules: [
                    {
                      required: true,
                      message: messages('common.please.select')
                    }
                  ]
                })(<Chooser
                  type="select_bank"
                  single={true}
                  disabled={bankInfo.id}
                  labelKey="bankBranchName"
                  placeholder={messages('common.please.select')}
                  valueKey="bankTypeBankCode"
                  listExtraParams={{isAll: true}}
                  onChange={this.handleBankChange}
                />)}
              </FormItem>
            </Col>
          </Row>

          {/*银行户名*/}
          <Row gutter={22}>
            <Col span={22}>
              <FormItem {...formItemLayout}
                        label={messages('financial-management.key318'/*银行户名*/)} colon={true}>
                {getFieldDecorator('venBankNumberName', {
                  initialValue: bankInfo.venBankNumberName,
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')
                  }]
                })(
                  <Input disabled={bankInfo.id} placeholder={messages('common.please.enter')}/>)}
              </FormItem>
            </Col>
          </Row>

          {/*银行账户*/}
          <Row gutter={22}>
            <Col span={22}>
              <FormItem {...formItemLayout}
                        label={messages('financial-management.key319'/*银行账号*/)} colon={true}>
                {getFieldDecorator('bankAccount', {
                  initialValue: bankInfo.bankAccount,
                  rules: [
                    {
                      required: true,
                      message: messages('common.please.enter')
                    },
                    {
                      max: 50,
                      message: messages('financial-management.key771')/*长度不能超过50*/
                    },
                    //任务编号 9661 银行账号校验必须包含数字
                    {
                      message: messages('financial-management.key320'/*必须包含数字*/),
                      validator: (rule, value, cb) => {
                        if (value === null || value === undefined || value === "") {
                          cb();
                          return;
                        }
                        let regExp = /[0-9]/;
                        //去掉空格
                        value = value.replace(/ /g, '');
                        if (regExp.test(value)) {
                          cb();
                        } else {
                          cb(false);
                        }
                      },
                    }
                  ]
                })(
                  <Input disabled={bankInfo.id} placeholder={messages('common.please.enter')}/>
                )}
              </FormItem>
            </Col>
          </Row>

          {/*国家*/}
          {/*是 disabled 的，原因不详。之前是付德宝开发的，就是如此，我只是把代码换行了*/}
          {/*其他字段的 disabled 是需求 5944*/}
          <Row gutter={22}>
            <Col span={22}>
              <FormItem {...formItemLayout}
                        label={messages('financial-management.key301'/*国家*/)} colon={true}>
                {getFieldDecorator('country', {
                  initialValue: bankInfo.country,
                })
                (<Select disabled allowClear showSearch onChange={this.countryChange}
                         placeholder={messages('common.please.select')}>
                  {country.map(item => (<Option value={item.key}>{item.label}</Option>))}
                </Select>)}
              </FormItem>
            </Col>
          </Row>
          {/*地址*/}
          <Row gutter={22}>
            <Col span={22}>
              <FormItem {...formItemLayout}
                        label={messages('financial-management.key321'/*地址*/)} colon={true}>
                {getFieldDecorator('bankAddress', {
                  initialValue: bankInfo.bankAddress
                })(
                  <Input disabled={bankInfo.id} placeholder={messages('common.please.enter')}/>)}
              </FormItem>
            </Col>
          </Row>

          {/*备注*/}
          <Row gutter={22}>
            <Col span={22}>
              <FormItem {...formItemLayout}
                        label={messages('financial-management.key322'/*备注*/)} colon={true}>
                {getFieldDecorator('notes', {
                  initialValue: bankInfo.notes
                })(
                  <TextArea placeholder={messages('common.please.enter')}/>)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={22}>
            <Col span={22}>
              <FormItem
                {...formItemLayout}
                label={messages('financial-management.key920')/*账户标志*/}
                colon={true}>
                {getFieldDecorator('accountMark', {
                  initialValue: bankInfo.accountMark,
                  rules: [
                    {
                      required: true,
                      message: messages('common.please.enter')
                    }
                  ]
                })(
                  <Select
                    showSearch
                    placeholder={messages('common.please.select')}
                    optionFilterProp="children"
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  >
                    {
                      this.renderCtripAccountOption(this.state.ctripList)
                    }
                  </Select>
                )
                }
              </FormItem>
            </Col>
          </Row>

          <div className="bank-account-tips">
            {messages('financial-management.key323'/*如果没有想要的银行，请联系集团管理员前往*/)}
            {messages('financial-management.key324'/*【银行定义】*/)}
            {messages('common.add')}
          </div>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages("common.save")}</Button>
            <Button onClick={this.onCancel}>{messages("common.cancel")}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

NewUpdateBankAccount.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    user: state.login.user
  }
}

const WrappedNewUpdateBankAccount = Form.create()(NewUpdateBankAccount);

export default connect(mapStateToProps)(WrappedNewUpdateBankAccount);
